from app import mongo
from decimal import Decimal
from datetime import datetime

def find_documents(collection_name, query, db_name='movies', sort=None):
    collection = mongo.cx[db_name][collection_name]
    if sort:
        results = collection.find(query).sort(sort)
    else:
        results = collection.find(query)
    return results

def insert_document(collection_name, data, db_name='movies'):
    collection = mongo.cx[db_name][collection_name]
    result = collection.insert_one(data)
    return result

def update_document(collection_name, query, update, db_name='movies'):
    collection = mongo.cx[db_name][collection_name]
    result = collection.update_many(query, {"$set": update})
    return result

def delete_document(collection_name, query, db_name='movies'):
    collection = mongo.cx[db_name][collection_name]
    result = collection.clear_collection(query)
    return result

def clear_collection(collection_name, db_name='movies'):
    collection = mongo.cx[db_name][collection_name]
    collection.clear_collection({})
    return True

def serialize_mysql(mysql_result):
    result = {}
    for key, value in mysql_result.__dict__.items():
        if key.startswith('_'):  # 排除 SQLAlchemy 的内部属性
            continue
        if isinstance(value, Decimal):
            value = float(value)
        elif isinstance(value, datetime):
            value = value.isoformat()  # 或直接用 value.strftime('%Y-%m-%d %H:%M:%S')
        result[key] = value
    return result
